﻿#!/usr/bin/env python
import hashlib
from Queue import *
import time
from control.log import mylog

#对象类
class Player():

    
    def __init__(self, name, gender):
        self.__name = str(name)
        self.__SetID()
        self.__sex  = gender
        #login time
        self.LoginTime = time.time()
        #上次来服务器取时间的时刻
        self.LastFetch = 0
        #缓存里需要送出的消息队列
        self.q = Queue(100)

    def __SetID(self):
        m = hashlib.md5()
        m.update(self.__name)
        self.__id = m.hexdigest()

    def SetSex(self, sex):
        self.__sex = sex

    def SetName(self, name):
        #修改名称后，一定需要更新ID
        self.__name == name
        self.__SetID()
        
    def GetObjID(self):
        return self.__id

    def GetObjSex(self):
        return self.__sex

    def GetObjName(self):
        return self.__name
    
    #def SetLogin(self, time):
    #    self.LoginTime = time

    def SetFetchTime(self, time):
        self.LastFetch = time

    def PushMsg(self, msg):
        self.q.put(msg)


#对象池
Capacity = 1000
class Pool():

    
    def __init__(self):
        self.__capacity = Capacity
        self.dic = {}
        self.__objcount = len(self.dic.keys())
        
    def GetCapacity(self):
        return self.__capacity

    def GetObjCount(self):
        return self.__objcount
    
    def IsFull(self):
        return self.__objcount >= self.__capacity

    def IsEmpty(self):
        return self.__objcount <= 0

    def AddObj(self, name, gender):
        if self.IsFull():
            mylog.error('pool is full:name(%s),gender(%s)'%(name,gender))
            return False
        obj = Player(name, gender)
        self.dic[obj.GetObjID()] = obj
        self.__objcount += 1
        mylog.info('Add object success:name(%s),gender(%s),len(%d)'%(name,gender,self.__objcount))
        return True

    def DelObj(self, id):
        del self.dic[id]
        self.__objcount -= 1

    def GetObj(self, id):
        return self.dic.get(id)

    #todo:每次取，都要遍历字典，可能会影响性能，暂时这样做
    def GetOnlineName(self):
        tmp = []
        for key in self.dic.keys():
            name = self.dic.get(key).GetObjName()
            tmp.append(name)
        return tmp
    
    def __del__(self):
        del self.dic


if __name__ == '__main__':
    cache = Pool()
    for i in xrange(1005):
        ret = cache.AddObj(i)
        if ret:
            pass
        else:
            print i
    print cache.GetObjCount()
